<template>
	<div class="community-public">
		<div class="community-public-container">
			<el-form :model="data" label-width="60px">
				<el-form-item label="描述">
					<commonEdit v-if="route.query.id >= 37 && route.query.id <= 53 || route.query.id >= 95 && route.query.id <= 136" :contentHtml="data.contentHtml" @onchange="editChange"></commonEdit>
					<commonNewEdit v-else :contentHtml="data.contentHtml" @onchange="editChange"></commonNewEdit>
				</el-form-item>
			</el-form>
			<el-form :model="data" label-width="120px">
				<el-form-item label="文章封面">
					<el-upload class="avatar-uploader" action="##" :show-file-list="false" :http-request="httpRequest"
						:before-upload="beforeAvatarUpload">
						<img v-if="imageUrl" :src="imageUrl" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="标题">
					<el-input v-model="data.title" placeholder="请输入标题" type="text" />
				</el-form-item>
				<el-form-item label="预览地址">
					<el-input v-model="data.previewAdress" placeholder="例如:https://www.baidu.cn/" type="text" />
				</el-form-item>
				<el-form-item label="源码地址">
					<el-input v-model="data.codeAdress" placeholder="例如:https://github.com/XXXX/XXXX.git" type="text" />
				</el-form-item>
				<el-form-item label="文章状态">
					<el-select v-model="data.public_status" class="m-2" size="large">
					    <el-option label="公开" :value="1"/>
						<el-option label="私密" :value="0"/>
					</el-select>
				</el-form-item>
				<el-form-item label="文章类型" v-if="store.state.userInfoX.user_type!=1">
					<el-select v-model="data.article_type" class="m-2" size="large">
					    <el-option label="普通" :value="1"/>
						<el-option v-if="store.state.userInfoX&&store.state.userInfoX.user_type!=1" label="新闻" :value="2"/>
						<el-option label="内推" :value="3"/>
						<el-option label="游戏" :value="4"/>
					</el-select>
				</el-form-item>
				<el-form-item label="工作地" v-if="data.article_type == 3">
					<el-cascader
						placeholder="请选择工作地址"
					    v-model="data.job_address"
					    :options="data.addressOptions"
					    @change="handleChange"></el-cascader>
				</el-form-item>
				<el-form-item label="职位" v-if="data.article_type == 3">
					<el-select v-model="data.job_type" @change="jobChange" filterable placeholder="请选择职位">
					    <el-option
					      v-for="item in data.jobOptions"
					      :key="item.value"
					      :label="item.label"
					      :value="item.value">
					    </el-option>
					  </el-select>
					<el-icon class="add-job" @click="addJobClick"><CirclePlusFilled /></el-icon>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSubmit" :loading="loading">{{data.publicText}}</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script lang="ts" setup>
	import commonEdit from "../../component/commonEdit.vue";
	import commonNewEdit from "../../component/commonNewEdit.vue";
	import city from "../../public/city"
	import {selectCity} from '../../public/selectCity'
	import {
		ref,
		reactive,
		inject,
		onBeforeMount,
		onMounted
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus,CirclePlusFilled
	} from '@element-plus/icons-vue'
	import type {
		UploadProps
	} from 'element-plus'
	import {
		HttpArticleRelease,
		HttpUpdateImage,
		HttpArticleDetails,
		HttpGetjobType,
		HttpJobType
	} from '../../public/http'
	
	import bus from '../../public/bus'
	import {useRoute,useRouter} from 'vue-router'
	const store = inject('store')
	const route = useRoute()
	const router = useRouter()
	const article_id = route.query.id
	

	let imageUrl = ref('')
	let loading = ref(false)
	let data = reactive({
		img_name: "",
		title: "",
		previewAdress: "",
		codeAdress: "",
		describe: "",
		publicText: "提交",
		public_status:1,
		article_type:1,
		job_address: "",
		job_type: "",
		contentHtml: "",
		addressOptions:[],
		jobOptions:[]
	})
	// 文章详情
	const articleDetailMain = ()=>{
		HttpArticleDetails(article_id).then((res:any)=>{
			if(res.code === 200){
				const {job_address,job_type_name,job_type,content,title,priview_address,code_address,image_name,image_path,public_status,article_type} = res.data.acticleDetail[0]
				data.contentHtml = content
				data.title = title
				data.previewAdress = priview_address
				data.codeAdress = code_address
				imageUrl.value = image_path
				data.img_name = image_name 
				data.public_status = Number(public_status) 
				data.article_type = Number(article_type) 
				data.job_address = job_address?job_address.split(','):job_address
				data.job_type = Number(job_type)
				data.job_type_name = job_type_name
			}
		})
	}
	// 富文本编辑框改变
	const editChange = (value: string) => {
	      data.contentHtml = value;
		  
	};
	// 选中的文字
	const jobChange = (val)=>{
		data.jobOptions.forEach((res)=>{
			if(res.value === val){
				data.job_type_name = res.label
			}
		})
		
		
	}
	const onSubmit = () => {
		if (!data.title) {
			ElMessage({
				message: '请输入文章标题!',
				type: 'warning',
			})
		} else if (!data.contentHtml) {
			ElMessage({
				message: '请填写描述信息!',
				type: 'warning',
			})
		} else if (data.article_type==3&&!data.job_address) {
			ElMessage({
				message: '请填写工作地址!',
				type: 'warning',
			})
		} else if (data.article_type==3&&!data.job_type) {
			ElMessage({
				message: '请填写职位!',
				type: 'warning',
			})
		} else {
			data.publicText = "提交中..."
			loading.value = true
			HttpArticleRelease({
				article_id:article_id,
				image_name: data.img_name,
				title: data.title,
				priview_address: data.previewAdress,
				code_address: data.codeAdress,
				content: data.contentHtml,
				public_status:data.public_status,
				article_type:data.article_type,
				job_address:data.article_type==3?data.job_address.toString():"",
				job_type:data.article_type==3?data.job_type:"",
				job_address_name:data.article_type==3?selectCity(data.job_address.toString()):"",
				job_type_name:data.job_type_name
			}).then((res: any) => {
				data.publicText = "提交"
				loading.value = false
				if (res.code === 200) {
					ElMessage({
						message: res.message,
						type: 'success',
					})
					bus.emit("reviseSuccess")
					router.push("/public")
					return
				}
				ElMessage({
					message: res.message,
					type: 'warning',
				})
			})
		}
	}

	const httpRequest = (files: any, uploadFile: any) => {
		let formdata = new FormData()
		formdata.append('files', files.file)
		HttpUpdateImage('articles', formdata).then((res: any) => {
			if (res.code === 200) {
				imageUrl.value = res.data.file_path
				data.img_name = res.data.file_name
				ElMessage({
					message: '上传成功',
					type: 'success',
				})
				return
			}
			ElMessage({
				message: res.message,
				type: 'warning',
			})
		})
	}

	const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
		if(!store.state.userInfoX.token){
			store.commit('isLogoutMain')
			return
		}
		if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
			ElMessage.error('头像必须是JPG/PNG!')
			return false
		}
		return true
	}
	// 获取城市、职位基本数据
	const getCityMain = async ()=>{
		let index = 0
		for(let k in city){
			
			data.addressOptions.push({
				label:city[k].name,
				value:k,
				children:[]
			})
			for(let c in city[k].child){
				data.addressOptions[index].children.push({
					label:city[k].child[c].name,
					value:c,
				})
			}
			index++
		}
		// 职位
		httpGetjobType()
	}
	const httpGetjobType = async ()=>{
		const result = await HttpGetjobType()
		data.jobOptions = []
		result.data.jobData.forEach((res)=>{
			data.jobOptions.push({
				label:res.name,
				value:res.id
			})
		})
	}
	// 添加职位
	const addJobClick = ()=>{
		ElMessageBox.prompt('添加职位', {
		    confirmButtonText: '确定',
		    cancelButtonText: '取消',
		    inputErrorMessage: '请输入职位名称',
		  })
		.then(({ value }) => {
			HttpJobType({
				name:value
			}).then((res)=>{
				if(res.code === 200){
					ElMessage({
						message: res.message,
						type: 'success',
					})
					httpGetjobType()
					return
				}
				ElMessage({
					message: res.message,
					type: 'warning',
				})
			})
		})
		.catch(() => {
		 
		})
	}
	onMounted(async()=>{
		
		getCityMain()
	})
	onBeforeMount(()=>{
		if(article_id){
			articleDetailMain()
		}
	})
</script>

<style lang="scss">
	.community-public {
		width: 100%;
		height: calc(100%);
		overflow: auto;
		background: #efedee;
		padding: 10px 10px 0 10px;
		box-sizing: border-box;
		
		.community-public-container{
			display: flex;
			justify-content: flex-start;
			width: 100%;
			.el-form--default{
				&:nth-of-type(1){
					width: 50%;
				}
			}
			.add-job{
				color: #409eff;
				font-size: 22px;
				margin-left: 10px;
				cursor: pointer;
				&:hover{
					opacity: 0.8;
				}
			}
		}
		.avatar-uploader {
			width: 178px;
			height: 178px;
			display: block;
			text-align: center;
			line-height: 178px;
			font-size: 30px;
			border: 1px;
			color: #8c939d;
			border: 1px dashed #d9d9d9;
			border-radius: 6px;
			cursor: pointer;

			.el-upload {
				width: 100%;
				height: 100%;

				img {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}
		}

		.el-form {
			margin-top: 30px;

			input {
				width: 300px;
				height: 40px;
			}

			textarea {
				width: 500px;
				height: 200px;
			}
		}
	}
</style>
